import axios from 'axios';
import { BASE_URL } from './config';
import { isDevelop } from '@/utils/setting';
import { PHP_SOCKET } from '$env';
import fastcgiAdapter from '@/api/fastcgiAdapter';

let requestParams = {};

const onRequest = (req) => {
  if (requestParams.headers.cookie) {
    req.headers.cookie = requestParams.headers.cookie;
  }
  // added http_x
  req.headers['user-agent'] = requestParams.headers['user-agent'];
  req.headers['accept-language'] = requestParams.headers['accept-language'];
  req.headers.host = requestParams.headers.host;
  // added cgi params
  req.cgiParams = {
    REMOTE_ADDR: requestParams.ip,
    SERVER_NAME: requestParams.hostname,
    NODEJS_VERSION: process.version,
  };
  return req;
};
const onRequestError = (err) => {
  return Promise.reject(err);
};

const onResponse = (res) => {
  return Promise.resolve(res);
};

const onResponseError = (err) => {
  return Promise.reject(err);
};

// 这是单实例 所以 cookie 必须动态变化
const createAxios = () => {
  let socketPath;
  if (isDevelop()) {
    socketPath = `/tmp/node-dev-operation-${process.pid}.sock`;
    // console.log(`axios create socket path ${socketPath}`);
  }
  const config = {
    baseURL: BASE_URL,
    timeout: 5000,
    socketPath,
    withCredentials: true,
  };
  if (PHP_SOCKET) {
    config.adapter = fastcgiAdapter;
    // console.log('API use Unix Domain Socket for axios fastcgi adapter.\n');
  }
  const http = axios.create(config);
  http.interceptors.request.use(onRequest, onRequestError);
  http.interceptors.response.use(onResponse, onResponseError);
  return http;
};

export const http = createAxios();

export const setApiParams = (req) => {
  requestParams = req;
  return http;
};
